package qe.spider.trade;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import lombok.extern.slf4j.Slf4j;
import org.ini4j.Ini;
import qe.spider.MainSelect;
import qe.spider.trade.huaxin.StockTradeHuaXin;
import qe.spider.trade.ths_lanzi.StockTradeTHSLanZi;
import qe.spider.vo.GoodStock;
import qe.spider.vo.Stock;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class SendBuySignal {
    public static String BaseTradePath = "D:\\Tools\\THSTrade\\";

    private static Ini ini;
    private static File csv;


    public static Ini getIni() throws IOException {
        if (ini == null)
            ini = new Ini(FileUtil.touch(BaseTradePath + System.getProperty("wsn_port", "8888") + "\\buy.ini"));
        return ini;
    }

    public static Boolean buy(GoodStock gs, Stock stock) throws IOException {
        try {
            record(gs); //记录到csv
        } catch (IOException e) {
            log.error("记录买入信号{}（{}）到csv出错", gs.getCode(), gs.getName(), e);
            e.printStackTrace();
        }
        String today = gs.getUpTime().substring(0, 10).replace("-", "");
        Ini ini = getIni();
        try {   //记录到ini买入信号
            Map<String, String> map = ini.get(today);
            if (null == map || (!map.containsKey(gs.getCode()) && map.size() < 5)) {
                ini.put(today, gs.getCode(), "1/5");
                ini.store();
            }
        } catch (IOException e) {
            log.error("记录买入信号{}（{}）到ini出错", gs.getCode(), gs.getName(), e);
            e.printStackTrace();
        }
        StockTradeHuaXin.accounts.values().stream().filter(t -> Optional.ofNullable(t.getCfg().getBuyStrategy()).orElse("shangbang_buy").contains("shangbang")).forEach(trade -> {
            try {
                trade.buy(stock);
            } catch (Exception e) {
                log.error("华鑫买入{}（{}）出错----账号：{}({})", gs.getCode(), gs.getName(), trade.getCfg().getUserName(), trade.getCfg().getUserId(), e);
            }
        });
        StockTradeTHSLanZi.accounts.values().stream().filter(t -> Optional.ofNullable(t.getCfg().getBuyStrategy()).orElse("shangbang_buy").contains("shangbang")).forEach(trade -> {
            try {
                trade.buy(stock);
            } catch (Exception e) {
                log.error("同花顺买入{}（{}）出错----账号：{}({})", gs.getCode(), gs.getName(), trade.getUserName(), trade.getUserId(), e);
            }
        });
        return ini.get(today).containsKey(gs.getCode());
    }

    public static File getCSV() throws IOException {
        if (csv == null) {
            csv = FileUtil.touch(BaseTradePath + System.getProperty("wsn_port", "8888") + "\\buy.csv");
            if (FileUtil.isEmpty(csv)) {
                FileUtil.writeString("股票代码,股票名称,买入信号产生日期,买入信号产生时间,上榜价格,上榜涨幅,上榜时的成交额,上榜时的主力净额,上榜时的主力净量,上榜时的主买占比,上榜时的主卖占比,上榜时的主力买,上榜时的主力卖,上榜时的换手率,所属板块,\r\n", csv, "GBK");
            }

        }
        return csv;
    }

    public static void record(GoodStock gs) throws IOException {
        CsvData data = CsvUtil.getReader(CsvReadConfig.defaultConfig().setContainsHeader(true)).read(getCSV(), Charset.forName("GBK"));
        List<CsvRow> stored = data.getRows().stream().filter(r -> r.getByName("股票代码").equals(gs.getCode()) && r.getByName("买入信号产生日期").equals(gs.getUpTime().substring(0, 10))).collect(Collectors.toList());
//        List<String> lines = FileUtil.readLines(getCSV(), "GBK");
//        List<String> stored = lines.stream().filter(line -> line.contains(gs.getCode()) && line.contains(gs.getUpTime().substring(0, 10))).collect(Collectors.toList());
        if (!stored.isEmpty()) return;  //已存当日该股，就不再保存了

        String recode = gs.getCode().replaceAll(",", "|") + ","
                + gs.getName().replaceAll(",", "|") + ","
                + gs.getUpTime().substring(0, 10) + ","
                + gs.getUpTime().substring(11) + ","
                + gs.getUpScore().replaceAll(",", "|") + ","
                + gs.getUpRate().replaceAll(",", "|") + ","
                + (gs.getVolume() == null ? "" : gs.getVolume().replaceAll(",", "|")) + ","
                + (gs.getZhuLiJingE() == null ? "" : gs.getZhuLiJingE().replaceAll(",", "|")) + ","
                + (gs.getZhuLiJingLiang() == null ? "" : gs.getZhuLiJingLiang().replaceAll(",", "|")) + ","
                + (gs.getZhuBuyZhanBi() == null ? "" : gs.getZhuBuyZhanBi().replaceAll(",", "|")) + ","
                + (gs.getZhuSellZhanBi() == null ? "" : gs.getZhuSellZhanBi().replaceAll(",", "|")) + ","
                + (gs.getZhuLiBuy() == null ? "" : gs.getZhuLiBuy().replaceAll(",", "|")) + ","
                + (gs.getZhuLiSell() == null ? "" : gs.getZhuLiSell().replaceAll(",", "|")) + ","
                + (gs.getShiJiHuanShouLv() == null ? "" : gs.getShiJiHuanShouLv().replaceAll(",", "|")) + ","
                + (gs.getPlate() == null ? "" : gs.getPlate().replaceAll(",", "|")) + ",\r\n";
        FileUtil.appendString(recode, getCSV(), "GBK");
    }
}
